import { createWebHashHistory, createRouter } from 'vue-router'
import { useRouterStore } from '@/store/route'
import { getFirstPage, addTrendsRouteList } from './utils'

const localRoutes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: () => import('@/views/login/index.vue'), meta: { title: '登录' } },
  { path: '/test/refer', component: () => import('@/views/test/refer.vue'), meta: { title: '参照测试' } },
  { path: '/test/virtualize', component: () => import('@/views/test/virtualize.vue'), meta: { title: '虚拟化' } },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: localRoutes,
})

const whiteList = ['/login', '/']
router.beforeEach(async (to, form, next) => {
  document.title = to.meta.title
  // 登录页面直接进入
  if (whiteList.includes(to.path)) {
    return next()
  }
  const { routes } = storeToRefs(useRouterStore())
  const localRoutes = router.getRoutes()
  // 是否执行完动态路由
  if (
    routes.value.length === 0
    || !localRoutes.some((item) => item.name === 'layout')
  ) {
    await addTrendsRouteList()
    if (form.path === '/login' || form.path === '/loginAdmin') {
      const firstPage = getFirstPage(routes.value)
      next(firstPage)

      return { path: firstPage }
    } else {
      next({ ...to })
    }
  } else {
    next()
  }
})
export default router
